//
//  ViewController1.m
//  MyWeChat
//
//  Created by 蔡欣东 on 15/10/5.
//  Copyright © 2015年 蔡欣东. All rights reserved.
//

#import "FriendListViewController.h"
#import "MyTableViewCell.h"
#import "UserInfo.h"
#import "XMPP.h"
#import "ChatViewController.h"
#import "PresenceDelegate.h"
#import "AppDelegate.h"
#import "MessageDelegate.h"

@interface FriendListViewController ()<UITableViewDataSource,UITableViewDelegate,PresenceDelegate,MessageInFriendListDelegate>{
    UITableView* _tableView;
    NSMutableArray* _tableSource;
}
@end

UserInfo* lordUser;
UserInfo* _friend;
ChatViewController* cvc;

@implementation FriendListViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    _tableSource = [[NSMutableArray alloc]init];

    _tableView = [[UITableView alloc]init];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    
    
    NSString* username = [[NSUserDefaults standardUserDefaults]valueForKey:USERNAME];
    lordUser = [[UserInfo alloc]initWithId:0 andName: username];

    self.view.backgroundColor = [UIColor whiteColor];
   [_tableView registerClass:MyTableViewCell.self forCellReuseIdentifier:[MyTableViewCell reuseIdentifier]];
    _tableView.frame = CGRectMake(0,35, self.view.frame.size.width, self.view.frame.size.height);
    
    UIView* headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,_tableView.frame.size.width, 10)];
    headerView.backgroundColor = [UIColor clearColor];
    _tableView.tableHeaderView = headerView;
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_tableView];

    
    UILabel* headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, 44)];
    headerLabel.backgroundColor = [UIColor whiteColor];
    headerLabel.font = [UIFont fontWithName:@"ChalkboardSE-Regular" size:18];
    headerLabel.text = @" Fiend list";
    headerLabel.textColor = [UIColor orangeColor];
    [self.view addSubview:headerLabel];
    
    ((AppDelegate*)[UIApplication sharedApplication].delegate).presenceDelegate = self;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getOtherMsg:) name:@"otherHaveNewMsg" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newTableResource:) name:@"releaseSource" object:nil];
    
}
-(void)viewDidAppear:(BOOL)animated{
    ((AppDelegate*)[UIApplication sharedApplication].delegate).messageInFriendListDelegate = self;
}
-(void)viewDidDisappear:(BOOL)animated{
    ((AppDelegate*)[UIApplication sharedApplication].delegate).messageInFriendListDelegate = nil;
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
#pragma mark - 通知后执行方法
-(void)newTableResource:(NSNotification*) noti{
    [_tableSource removeAllObjects];
}
-(void)getOtherMsg:(NSNotification*) noti{
    //_friend = (UserInfo*)noti.userInfo[@"otherInfo"];
    NSLog(@"当前好友是%@",_friend.name);
    [_tableView reloadData];
    NSLog(@"yes %@",noti.userInfo);
}
#pragma mark - tableView Delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _tableSource.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [MyTableViewCell heightForCell];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MyTableViewCell* cell = [_tableView dequeueReusableCellWithIdentifier:[MyTableViewCell reuseIdentifier]];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UserInfo* getUser = (UserInfo*)[_tableSource objectAtIndex:indexPath.row];
    if (_tableSource.count>0) {
        [cell setupCell: getUser];
    }
    if ([getUser.name isEqual:_friend.name]) {
        cell.tipView.hidden = NO;
    }
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UserInfo* user = (UserInfo*)_tableSource[indexPath.row];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]init];
    item.title = @"";
    self.navigationItem.backBarButtonItem = item;
    ((MyTableViewCell*)[tableView cellForRowAtIndexPath:indexPath]).tipView.hidden = YES;
    cvc = [[ChatViewController alloc]init];
    [cvc chatFriendDidChange:user];
    //[cvc.tableView reloadData];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:cvc animated:YES];
}
#pragma mark - present delegate
-(void)presenceDidChange:(UserInfo *)friend{
    NSArray* temp = [NSArray arrayWithArray:_tableSource];//debug:Collection <__NSArrayM: 0x7fbaa9415b30> was mutated while being enumerated.
    for (UserInfo* user in temp) {
        if ([user.name isEqual:friend.name]) {
            [_tableSource removeObject:user];
        }
    }
    [_tableSource insertObject:friend atIndex:0];
    [_tableView reloadData];
}
#pragma mark -message delegate
-(void)didRecieveMessageInFriendList:(MessageInfo *)messageInfo{
    NSLog(@"new message");
    [self putInUserDefault:messageInfo];
    _friend = messageInfo.user;
    [_tableView reloadData];
    
}
#pragma mark - 消息储存到 NSUserDefaults
-(void)putInUserDefault:(MessageInfo*)message{
    NSMutableArray* chatInfo = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:[NSString stringWithFormat:@"%@and%@msg",lordUser.name,message.user.name]]];
    NSMutableArray* chatUser = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:[NSString stringWithFormat:@"%@and%@",lordUser.name,message.user.name]]];
    [chatInfo addObject:message.messageBody];
    [chatUser addObject:message.user.name];
    NSLog(@"friendlist储存的消息是%@",message.messageBody);
    NSLog(@"消息的主人是%@",message.user.name);
    [[NSUserDefaults standardUserDefaults]setObject:chatInfo forKey:[NSString stringWithFormat:@"%@and%@msg",lordUser.name,message.user.name]];
    [[NSUserDefaults standardUserDefaults]setObject:chatUser forKey:[NSString stringWithFormat:@"%@and%@",lordUser.name,message.user.name]];
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSLog(@"userdefault内容有%@",[NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:[NSString stringWithFormat:@"%@and%@msg",lordUser.name,message.user.name]]][0]);
}


@end
